const mysql = require('mysql2/promise')

// 创建数据库连接池（不指定数据库）
const initialPool = mysql.createPool({
  host: '127.0.0.1',
  user: 'root',
  password: 'wxy12345',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
})

// 创建数据库
const createDatabase = async () => {
  try {
    const connection = await initialPool.getConnection()
    await connection.query(`
      CREATE DATABASE IF NOT EXISTS ai_chat
      CHARACTER SET utf8mb4
      COLLATE utf8mb4_unicode_ci
    `)
    console.log('数据库创建成功')
    connection.release()
  } catch (err) {
    console.error('数据库创建失败:', err.message)
    throw err  // 抛出错误而不是退出程序
  }
}

// 创建实际使用的连接池（指定数据库）
const pool = mysql.createPool({
  host: '127.0.0.1',
  user: 'root',
  password: 'wxy12345',
  database: 'ai_chat',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
})

const connectDB = async () => {
  try {
    // 先创建数据库
    await createDatabase()

    // 然后连接到数据库
    const connection = await pool.getConnection()
    console.log('MySQL连接成功')
    connection.release()
  } catch (err) {
    console.error('MySQL连接失败:', err.message)
    throw err  // 抛出错误而不是退出程序
  }
}

// 创建数据库表
const initDB = async () => {
  try {
    const connection = await pool.getConnection()

    // 创建用户表
    await connection.query(`
      CREATE TABLE IF NOT EXISTS users (
        id INT PRIMARY KEY AUTO_INCREMENT,
        username VARCHAR(50) UNIQUE NOT NULL,
        email VARCHAR(100) UNIQUE NOT NULL,
        password VARCHAR(255) NOT NULL,
        api_key VARCHAR(255) DEFAULT '',
        theme VARCHAR(20) DEFAULT 'dark',
        model VARCHAR(50) DEFAULT 'deepseek-chat',
        temperature FLOAT DEFAULT 0.7,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      )
    `)

    // 创建聊天记录表
    await connection.query(`
      CREATE TABLE IF NOT EXISTS chats (
        id INT PRIMARY KEY AUTO_INCREMENT,
        user_id INT NOT NULL,
        title VARCHAR(255) DEFAULT '新对话',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES users(id)
      )
    `)

    // 创建消息表
    await connection.query(`
      CREATE TABLE IF NOT EXISTS messages (
        id INT PRIMARY KEY AUTO_INCREMENT,
        chat_id INT NOT NULL,
        role ENUM('user', 'assistant') NOT NULL,
        content TEXT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        session_id INT NOT NULL DEFAULT 0,
        FOREIGN KEY (chat_id) REFERENCES chats(id) ON DELETE CASCADE
      )
    `)

    connection.release()
    console.log('数据库表创建成功')
  } catch (err) {
    console.error('数据库表创建失败:', err.message)
    throw err  // 抛出错误而不是退出程序
  }
}

module.exports = { pool, connectDB, initDB }
